package com.crack.nga2.volley;

import android.text.SpannableStringBuilder;
import android.util.Log;

import com.android.volley.NetworkResponse;
import com.android.volley.Response;
import com.android.volley.toolbox.HttpHeaderParser;
import com.crack.nga2.entity.CustomLevel;
import com.crack.nga2.entity.Floor;
import com.crack.nga2.entity.Medal;
import com.crack.nga2.entity.User;
import com.crack.nga2.entity.data.FloorData;
import com.crack.nga2.entity.data.ReadThemeData;
import com.crack.nga2.span.SpanHelper;
import com.crack.nga2.span.SpanUtil;
import com.crack.nga2.utils.DataUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 阅读主题请求
 * Created by Administrator on 2016/1/5.
 */
public class ReadThemeRequest extends BaseRequest<FloorData> {
    private Response.Listener<FloorData> listener;
    private SpanHelper helper;

    public ReadThemeRequest(int method, String url, Response.ErrorListener errorListener, Response.Listener<FloorData> listener, SpanHelper helper) {
        super(method, url, errorListener);
        this.listener = listener;
        this.helper = helper;
    }


    @Override
    protected Response<FloorData> parseNetworkResponse(NetworkResponse response) {
        String json;
        try {
            json = new String(response.data, "GBK");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
        FloorData floorData = new FloorData();
        json = DataUtil.getData(json);
        //去掉一些会造成解析异常的数据（如本来应该是Object的数据变为了空字符串"1":""）
        json = json.replaceAll(",\"\\d+\":\"\"", "");
        Log.i("floorAc", json);
        Gson gson = new Gson();
        Type type = new TypeToken<ReadThemeData>() {
        }.getType();
        ReadThemeData data = gson.fromJson(json, type);
        //楼层数据
        Map<Integer, Floor> floors = data.get__R();
        //自定义声望
        CustomLevel __F = data.__F;
        String customLevelJson = __F.getCustom_level();
        if (customLevelJson != null) {
            __F.sections = new Gson().fromJson(customLevelJson, new TypeToken<List<CustomLevel.LevelSection>>() {
            }.getType());
            Collections.sort(__F.sections);
        }
        //贴子数据
        //用户及相关信息数据

        Map<String, Object> __U = data.get__U();
        //用户组
        Map<Integer, User> users = new HashMap<>();
        // 用户组
        Map<Integer, Map<Integer, String>> groups = null;
        // 徽章
        Map<Integer, Map<Integer, String>> medals = null;
        // 威望
        Map<Integer, Map<Integer, String>> reputations = null;
        //分别赋值
        for (Map.Entry<String, Object> entry : __U.entrySet()) {
            String key = entry.getKey();
            Object object = entry.getValue();
            if (key.matches("[0-9]+")) {
                String string = gson.toJson(object);
                User user = gson.fromJson(string, User.class);
                users.put(Integer.parseInt(key), user);
            } else {
                Type typeOf = new TypeToken<Map<Integer, Map<Integer, String>>>() {
                }.getType();
                String string = gson.toJson(object);
                switch (key) {
                    case "__GROUPS":
                        groups = gson.fromJson(string, typeOf);
                        break;
                    case "__MEDALS":
                        medals = gson.fromJson(string, typeOf);
                        break;
                    case "__REPUTATIONS":
                        reputations = gson.fromJson(string, typeOf);
                        break;
                }
            }
        }
        Map<Integer, String> user_reputations = new HashMap<>();
        if (reputations != null) {
            for (Map.Entry<Integer, Map<Integer, String>> entry : reputations.entrySet()) {
                user_reputations = entry.getValue();
            }
        }
        //设置声望以及可能存在的自定义等级名称
        for (Map.Entry<Integer, User> entry : users.entrySet()) {
            int id = entry.getKey();
            User user = entry.getValue();
            String reputation = user_reputations.get(id);
            int rep = 0;
            if (reputation != null && reputation.matches("[\\d\\.]+")) {
                rep = (int) Double.parseDouble(reputation);
                user.setF_reputation(rep);
            }
            //寻找对应用户组的名称
            if (__F.sections != null) {
                if (rep >= 0) {
                    for (int i = __F.sections.size() - 1; i >= 0; i--) {
                        if (rep >= __F.sections.get(i).r) {
                            user.setF_level(__F.sections.get(i).n);
                            break;
                        }
                    }
                } else {
                    for (int i = 0; i < __F.sections.size() - 1; i++) {
                        if (rep <= __F.sections.get(i).r) {
                            user.setF_level(__F.sections.get(i).n);
                            break;
                        }
                    }
                }
            } else {
                //如果没有自定义声望名称 则设置用户组名称
                int groupId = user.getGroupid() != -1 ? user.getGroupid() : user.getMemberid();
                if (groups != null && groups.get(groupId) != null) {
                    user.setF_level(groups.get(groupId).get(ReadThemeData.GROUP_NAME));
                }
            }
        }
        //设置用户徽章数据
        Map<Integer, Medal> medalMap = new HashMap<>();
        if (medals != null) {
            for (Map.Entry<Integer, Map<Integer, String>> entry : medals.entrySet()) {
                int id = entry.getKey();
                Map<Integer, String> value = entry.getValue();
                if (value != null) {
                    Medal medal = new Medal();
                    medal.icon = value.get(0);
                    medal.name = value.get(1);
                    medal.description = value.get(2);
                    medal.id = value.get(3);
                    medalMap.put(id, medal);
                }
            }
        }
        //设置楼层数据
        List<Floor> list = new ArrayList<>();
        for (Map.Entry<Integer, Floor> entry : floors.entrySet()) {
            Floor floor = entry.getValue();
            if (floor != null) {
                String content = floor.getContent();
                if (content != null) {
                    //解析标签
                    floor.setSp(SpanUtil.formatSpan(content, helper.emotionGetter, helper.pidClick, helper.uidClick, helper.urlClick));
                    //提取引用内容 TODO
                    SpannableStringBuilder quote = SpanUtil.getQuote(floor.getSp());
                    floor.setQuote(quote);
                }
            }
            list.add(floor);
        }
        Collections.sort(list, new Comparator<Floor>() {
            @Override
            public int compare(Floor lhs, Floor rhs) {
                return lhs.getLou() - rhs.getLou();
            }
        });
        floorData.theme = data.get__T();
        floorData.floors = list;
        floorData.medals = medalMap;
        floorData.users = users;
        return Response.success(floorData, HttpHeaderParser.parseCacheHeaders(response));
    }

    @Override
    protected void deliverResponse(FloorData response) {
        if(listener!=null){
            listener.onResponse(response);
        }
    }
}
